#include "snake.h"
#include <SFML/Graphics.hpp>
#include <iostream>
#include <algorithm>

Snake::Snake(int startX, int startY, Direction initialDir, sf::Color snakeColor, sf::Color snakeBorderColor)
    : dir(initialDir), nextDir(initialDir), color(snakeColor), borderColor(snakeBorderColor) {
    // 初始化蛇身（长度为3）
    body.push_back(Point(startX, startY));
    body.push_back(Point(startX - 1, startY));
    body.push_back(Point(startX - 2, startY));
}

void Snake::move(const Point& food, bool grow) {
    // 更新方向
    dir = nextDir;
    
    // 计算新头部位置
    Point newHead = getHead();
    switch (dir) {
    case LEFT:  newHead.x--; break;
    case RIGHT: newHead.x++; break;
    case UP:    newHead.y--; break;
    case DOWN:  newHead.y++; break;
    default: break;
    }
    
    // 屏幕环绕（从一侧穿出，从另一侧进入）
    if (newHead.x < 0) newHead.x = WIDTH - 1;
    else if (newHead.x >= WIDTH) newHead.x = 0;
    if (newHead.y < 0) newHead.y = HEIGHT - 1;
    else if (newHead.y >= HEIGHT) newHead.y = 0;
    
    // 添加新头部
    body.insert(body.begin(), newHead);
    
    // 如果没有吃到食物，移除尾部
    if (!grow) {
        body.pop_back();
    }
}

void Snake::draw(sf::RenderWindow& window) {
    for (const auto& point : body) {
        sf::RectangleShape segment(sf::Vector2f(BLOCK_SIZE, BLOCK_SIZE));
        segment.setPosition(static_cast<float>(point.x * BLOCK_SIZE), static_cast<float>(point.y * BLOCK_SIZE + PANEL_HEIGHT));
        segment.setFillColor(color);
        segment.setOutlineColor(borderColor);
        segment.setOutlineThickness(1);
        window.draw(segment);
    }
}

bool Snake::checkCollision(const Point& point) const {
    // 检查点是否与蛇身碰撞
    return std::find(body.begin(), body.end(), point) != body.end();
}

bool Snake::checkSelfCollision(const Point& head) const {
    // 检查头部是否与身体其他部分碰撞
    for (size_t i = 1; i < body.size(); i++) {
        if (body[i] == head) {
            return true;
        }
    }
    return false;
}

Point Snake::getHead() const {
    return body.front();
}

Direction Snake::getDirection() const {
    return dir;
}

void Snake::setDirection(Direction direction) {
    dir = direction;
}

Direction Snake::getNextDirection() const {
    return nextDir;
}

void Snake::setNextDirection(Direction direction) {
    nextDir = direction;
}

const std::vector<Point>& Snake::getBody() const {
    return body;
}

void Snake::reset(int startX, int startY, Direction initialDir) {
    body.clear();
    dir = initialDir;
    nextDir = initialDir;
    
    // 重新初始化蛇身（长度为3）
    body.push_back(Point(startX, startY));
    body.push_back(Point(startX - 1, startY));
    body.push_back(Point(startX - 2, startY));
}

// 颜色定义
const sf::Color SNAKE_COLOR = sf::Color(0, 255, 0);
const sf::Color SNAKE_BORDER_COLOR = sf::Color::White;
const sf::Color FOOD_COLOR = sf::Color(255, 0, 0);
const sf::Color FOOD_BORDER_COLOR = sf::Color::Yellow;
const sf::Color BORDER_COLOR = sf::Color::White;
const sf::Color AISNAKE_COLOR = sf::Color(0, 0, 255);
const sf::Color AISNAKE_BORDER_COLOR = sf::Color::White;
const sf::Color ROBOTSNAKE_COLOR = sf::Color(128, 0, 128);
const sf::Color ROBOTSNAKE_BORDER_COLOR = sf::Color::White;
const sf::Color PLAYER_SCORE_COLOR = sf::Color::Yellow;
const sf::Color AI_SCORE_COLOR = sf::Color::Cyan;

// 窗口尺寸
const int WIDTH = 65;
const int HEIGHT = 35;
const int BLOCK_SIZE = 20;
const int PANEL_HEIGHT = 50;
const int BASE_SPEED = 150;

// 方向定义
enum Direction { STOP = 0, LEFT, RIGHT, UP, DOWN };

// 坐标结构体
struct Point {
    int x, y;
    Point(int x = 0, int y = 0) : x(x), y(y) {}
    bool operator==(const Point& other) const {
        return x == other.x && y == other.y;
    }
};

// 蛇类
class Snake {
private:
    std::vector<Point> body;
    Direction dir;
    Direction nextDir;
    sf::Color color;
    sf::Color borderColor;

public:
    Snake(int startX, int startY, Direction initialDir, sf::Color snakeColor, sf::Color snakeBorderColor);

    void move(const Point& food, bool grow);
    void draw(sf::RenderWindow& window);
    bool checkCollision(const Point& point) const;
    bool checkSelfCollision(const Point& head) const;
    Point getHead() const;
    Direction getDirection() const;
    void setDirection(Direction direction);
    Direction getNextDirection() const;
    void setNextDirection(Direction direction);
    const std::vector<Point>& getBody() const;
    void reset(int startX, int startY, Direction initialDir);
};

// 游戏类
class Game {
private:
    bool gameOver = false;
    bool gameStarted = false;
    Point food;
    int playerScore = 0;
    int ai1Score = 0;
    int ai2Score = 0;
    sf::RenderWindow window;
    std::mt19937 rng;
    sf::Font font;
    int gameSpeed = BASE_SPEED;

    Snake playerSnake;
    Snake ai1Snake;
    Snake ai2Snake;

    int ai1DirFrames = 0;
    const int MIN_DIR_FRAMES = 3;

    int ai2DirFrames = 0;

    // 单人模式按钮
    sf::RectangleShape singlePlayerButton;
    sf::Text singlePlayerText;
    bool singlePlayerButtonHovered = false;
    // 局域网模式按钮
    sf::RectangleShape onlineModeButton;   
    sf::Text onlineModeText;               
    bool onlineModeButtonHovered = false;  
    bool isOnlineMode = false;            

    // AI1方向决策（追逐食物）
    Direction getAIDirection(const Snake& ai, Direction currentDir, int& dirFrames) {
        Point head = ai.getHead();
        int dx = food.x - head.x;
        int dy = food.y - head.y;

        // 计算当前方向的下一个位置
        Point currentDirPos = head;
        switch (currentDir) {
        case LEFT:  currentDirPos.x--; break;
        case RIGHT: currentDirPos.x++; break;
        case UP:    currentDirPos.y--; break;
        case DOWN:  currentDirPos.y++; break;
        default: return RIGHT;
        }

        // 确保方向至少保持MIN_DIR_FRAMES帧，避免频繁转向
        if (dirFrames < MIN_DIR_FRAMES) {
            if (isSafe(currentDirPos, ai.getBody())) {
                dirFrames++;
                return currentDir;
            }
            else {
                dirFrames = 0;
            }
        }
        else {
            dirFrames = 0;
        }

        // 检查当前方向是否朝向食物
        bool isTowardFood = false;
        switch (currentDir) {
        case LEFT:  isTowardFood = (dx < 0); break;
        case RIGHT: isTowardFood = (dx > 0); break;
        case UP:    isTowardFood = (dy < 0); break;
        case DOWN:  isTowardFood = (dy > 0); break;
        }
        if (isSafe(currentDirPos, ai.getBody()) && isTowardFood) {
            dirFrames++;
            return currentDir;
        }

        // 优先沿X轴（水平）向食物移动
        if (abs(dx) >= abs(dy)) {
            if (dx > 0 && currentDir != LEFT) {
                Point nextPos(head.x + 1, head.y);
                if (isSafe(nextPos, ai.getBody())) return RIGHT;
            }
            if (dx < 0 && currentDir != RIGHT) {
                Point nextPos(head.x - 1, head.y);
                if (isSafe(nextPos, ai.getBody())) return LEFT;
            }
            if (dy > 0 && currentDir != UP) {
                Point nextPos(head.x, head.y + 1);
                if (isSafe(nextPos, ai.getBody())) return DOWN;
            }
            if (dy < 0 && currentDir != DOWN) {
                Point nextPos(head.x, head.y - 1);
                if (isSafe(nextPos, ai.getBody())) return UP;
            }
        }
        // 优先沿Y轴（垂直）向食物移动
        else {
            if (dy > 0 && currentDir != UP) {
                Point nextPos(head.x, head.y + 1);
                if (isSafe(nextPos, ai.getBody())) return DOWN;
            }
            if (dy < 0 && currentDir != DOWN) {
                Point nextPos(head.x, head.y - 1);
                if (isSafe(nextPos, ai.getBody())) return UP;
            }
            if (dx > 0 && currentDir != LEFT) {
                Point nextPos(head.x + 1, head.y);
                if (isSafe(nextPos, ai.getBody())) return RIGHT;
            }
            if (dx < 0 && currentDir != RIGHT) {
                Point nextPos(head.x - 1, head.y);
                if (isSafe(nextPos, ai.getBody())) return LEFT;
            }
        }

        // 若无最优路径，随机选择一个安全方向
        std::vector<Direction> possibleDirs = { LEFT, RIGHT, UP, DOWN };
        std::shuffle(possibleDirs.begin(), possibleDirs.end(), rng);
        for (auto d : possibleDirs) {
            if ((d == LEFT && currentDir != RIGHT) || (d == RIGHT && currentDir != LEFT) ||
                (d == UP && currentDir != DOWN) || (d == DOWN && currentDir != UP)) {
                Point nextPos = head;
                switch (d) {
                case LEFT: nextPos.x--; break;
                case RIGHT: nextPos.x++; break;
                case UP: nextPos.y--; break;
                case DOWN: nextPos.y++; break;
                default: break;
                }
                if (isSafe(nextPos, ai.getBody())) return d;
            }
        }
        return currentDir;
    }

    // AI2方向决策（优先躲避玩家，再追逐食物）
    Direction getAI2Direction() {
        Point head = ai2Snake.getHead();
        Point playerHead = playerSnake.getHead();
        int dxPlayer = playerHead.x - head.x;
        int dyPlayer = playerHead.y - head.y;

        // 若距离玩家小于等于3格，优先躲避
        if (abs(dxPlayer) + abs(dyPlayer) <= 3) {
            if (dxPlayer > 0 && ai2Snake.getDirection() != RIGHT) {
                Point nextPos(head.x - 1, head.y);
                if (isSafe(nextPos, ai2Snake.getBody())) {
                    ai2DirFrames = 0;
                    return LEFT;
                }
            }
            if (dxPlayer < 0 && ai2Snake.getDirection() != LEFT) {
                Point nextPos(head.x + 1, head.y);
                if (isSafe(nextPos, ai2Snake.getBody())) {
                    ai2DirFrames = 0;
                    return RIGHT;
                }
            }
            if (dyPlayer > 0 && ai2Snake.getDirection() != DOWN) {
                Point nextPos(head.x, head.y - 1);
                if (isSafe(nextPos, ai2Snake.getBody())) {
                    ai2DirFrames = 0;
                    return UP;
                }
            }
            if (dyPlayer < 0 && ai2Snake.getDirection() != UP) {
                Point nextPos(head.x, head.y + 1);
                if (isSafe(nextPos, ai2Snake.getBody())) {
                    ai2DirFrames = 0;
                    return DOWN;
                }
            }
        }

        // 玩家安全时，按AI1逻辑追逐食物
        return getAIDirection(ai2Snake, ai2Snake.getDirection(), ai2DirFrames);
    }

    // 检查位置是否安全（无边界碰撞、无自身碰撞、无其他蛇碰撞）
    bool isSafe(const Point& pos, const std::vector<Point>& selfBody) {
        // 边界碰撞
        if (pos.x < 0 || pos.x >= WIDTH || pos.y < 0 || pos.y >= HEIGHT)
            return false;

        // 自身碰撞
        if (std::find(selfBody.begin(), selfBody.end(), pos) != selfBody.end())
            return false;

        // 其他蛇碰撞
        if (playerSnake.checkCollision(pos))
            return false;
        if (ai1Snake.checkCollision(pos))
            return false;
        if (ai2Snake.checkCollision(pos))
            return false;
        return true;
    }

    // 初始化按钮
    void initButtons() {
        // 单人模式按钮
        singlePlayerButton.setSize(sf::Vector2f(200, 50));
        singlePlayerButton.setPosition(WIDTH * BLOCK_SIZE / 2 - 100, HEIGHT * BLOCK_SIZE / 2 - 20 + PANEL_HEIGHT);
        singlePlayerButton.setFillColor(sf::Color(50, 50, 50)); // 默认深灰色
        singlePlayerButton.setOutlineColor(sf::Color::White);
        singlePlayerButton.setOutlineThickness(2);
        //局域网模式按钮
        onlineModeButton.setSize(sf::Vector2f(200, 50)); 
        onlineModeButton.setPosition(
            WIDTH * BLOCK_SIZE / 2 - 100,
            HEIGHT * BLOCK_SIZE / 2 - 20 + PANEL_HEIGHT + 50 + 20
        );
        onlineModeButton.setFillColor(sf::Color(50, 50, 50)); 
        onlineModeButton.setOutlineColor(sf::Color::White);
        onlineModeButton.setOutlineThickness(2);
        // 按钮文本（字体加载成功时）
        if (font.getInfo().family != "") {
            singlePlayerText.setFont(font);
            singlePlayerText.setString("SINGLE PLAYER");
            singlePlayerText.setCharacterSize(24);
            singlePlayerText.setFillColor(sf::Color::White);
            sf::FloatRect textRect = singlePlayerText.getLocalBounds();
            singlePlayerText.setOrigin(textRect.width / 2, textRect.height / 2);
            singlePlayerText.setPosition(WIDTH * BLOCK_SIZE / 2, HEIGHT * BLOCK_SIZE / 2 + PANEL_HEIGHT);
            onlineModeText.setFont(font);
            onlineModeText.setString("ONLINE MODE"); 
            onlineModeText.setCharacterSize(24);
            onlineModeText.setFillColor(sf::Color::White);
            sf::FloatRect onlineTextRect = onlineModeText.getLocalBounds();
            onlineModeText.setOrigin(onlineTextRect.width / 2, onlineTextRect.height / 2);
            onlineModeText.setPosition(
                WIDTH * BLOCK_SIZE / 2,
                HEIGHT * BLOCK_SIZE / 2 - 20 + PANEL_HEIGHT + 50 + 20 + 25
            );
        }
    }

public:
    // 构造函数（初始化窗口、蛇、食物、字体）
    Game() : window(sf::VideoMode(WIDTH* BLOCK_SIZE, HEIGHT* BLOCK_SIZE + PANEL_HEIGHT), "SFML Snake"),
             playerSnake(WIDTH / 2, HEIGHT / 4, RIGHT, SNAKE_COLOR, SNAKE_BORDER_COLOR),
             ai1Snake(WIDTH / 4, HEIGHT / 2, RIGHT, AISNAKE_COLOR, AISNAKE_BORDER_COLOR),
             ai2Snake(3 * WIDTH / 4, HEIGHT / 2, LEFT, ROBOTSNAKE_COLOR, ROBOTSNAKE_BORDER_COLOR) {
        // 初始化随机数生成器
        rng.seed(static_cast<unsigned int>(std::time(nullptr)));

        // 加载系统字体（多路径 fallback，适配不同Windows环境）
        std::vector<std::string> fontPaths = {
            "C:\\Windows\\Fonts\\simhei.ttf",
            "C:\\Windows\\Fonts\\msyh.ttc",
            "C:\\Windows\\Fonts\\arial.ttf",
            "C:\\Windows\\Fonts\\times.ttf",
            "C:\\Windows\\Fonts\\simsun.ttc"
        };
        bool fontLoaded = false;
        for (const auto& path : fontPaths) {
            if (font.loadFromFile(path)) {
                // 修复：中文输出用ASCII兼容格式，避免编码截断
                std::cout << "Cheng Gong Jia Zai Zi Ti: " << path << std::endl;
                fontLoaded = true;
                break;
            }
        }
        if (!fontLoaded) {
            // 修复：中文输出用ASCII兼容格式，避免编码截断
            std::cerr << "Jing Gao: Zi Ti Jia Zai Shi Bai, Wu Fa Xian Shi Wen Ben!" << std::endl;
        }

        // 生成初始食物
        generateFood();
        // 修复：中文输出用ASCII兼容格式，避免编码截断
        std::cout << "Chu Shi Shi Wu Wei Zhi: (" << food.x << ", " << food.y << ")" << std::endl;

        // 初始化按钮
        initButtons();
    }

    // 生成食物（避免落在蛇身上）
    void generateFood() {
        bool validPos;
        int attempts = 0;
        do {
            validPos = true;
            // 随机生成食物坐标（在游戏区域内）
            food.x = rng() % WIDTH;
            food.y = rng() % HEIGHT;

            // 检查食物是否落在任意蛇身上
            if (playerSnake.checkCollision(food) ||
                ai1Snake.checkCollision(food) ||
                ai2Snake.checkCollision(food)) {
                validPos = false;
                attempts++;
            }

            // 尝试超过10次时强制生成（避免无限循环）
            if (attempts > 10) {
                validPos = true;
                // 修复：中文输出用ASCII兼容格式，避免编码截断
                std::cout << "Jing Gao: Shi Wu Sheng Cheng Chang Shi Guo Duo, Ke Neng Chong Die!" << std::endl;
            }
        } while (!validPos);
        // 修复：中文输出用ASCII兼容格式，避免编码截断
        std::cout << "Sheng Cheng Shi Wu Wei Zhi: (" << food.x << ", " << food.y << ")" << std::endl;
    }

    // 处理输入（键盘+鼠标）
    void handleInput() {
        sf::Event event;
        while (window.pollEvent(event)) {
            // 关闭窗口
            if (event.type == sf::Event::Closed) {
                window.close();
                gameOver = true;
                return;
            }

            // 键盘输入（游戏中）
            if (event.type == sf::Event::KeyPressed) {
                if (gameStarted) {
                    switch (event.key.code) {
                    case sf::Keyboard::A: if (playerSnake.getDirection() != RIGHT) playerSnake.setNextDirection(LEFT); break;
                    case sf::Keyboard::D: if (playerSnake.getDirection() != LEFT) playerSnake.setNextDirection(RIGHT); break;
                    case sf::Keyboard::W: if (playerSnake.getDirection() != DOWN) playerSnake.setNextDirection(UP); break;
                    case sf::Keyboard::S: if (playerSnake.getDirection() != UP) playerSnake.setNextDirection(DOWN); break;
                    case sf::Keyboard::X: gameOver = true; break;
                    }
                }
            }

            // 鼠标移动事件 - 处理按钮悬停
            else if (event.type == sf::Event::MouseMoved) {
                if (!gameStarted) {
                    sf::Vector2i mousePos = sf::Mouse::getPosition(window);
                    if (singlePlayerButton.getGlobalBounds().contains(static_cast<float>(mousePos.x), static_cast<float>(mousePos.y))) {
                        singlePlayerButtonHovered = true;
                        singlePlayerButton.setFillColor(sf::Color(80, 80, 80)); // 悬停时浅灰色
                    }
                    else {
                        singlePlayerButtonHovered = false;
                        singlePlayerButton.setFillColor(sf::Color(50, 50, 50)); // 默认深灰色
                    }
                    if (onlineModeButton.getGlobalBounds().contains(static_cast<float>(mousePos.x), static_cast<float>(mousePos.y))) {
                        onlineModeButtonHovered = true;
                        onlineModeButton.setFillColor(sf::Color(80, 80, 80)); // 悬停浅灰色
                    }
                    else {
                        onlineModeButtonHovered = false;
                        onlineModeButton.setFillColor(sf::Color(50, 50, 50)); // 默认深灰色
                    }
                }         
            }

            // 鼠标点击事件 - 处理按钮点击
            else if (event.type == sf::Event::MouseButtonPressed) {
                if (!gameStarted && event.mouseButton.button == sf::Mouse::Left) {
                    sf::Vector2i mousePos = sf::Mouse::getPosition(window);
                    if (singlePlayerButton.getGlobalBounds().contains(static_cast<float>(mousePos.x), static_cast<float>(mousePos.y))) {
                        gameStarted = true;
                        playerSnake.setDirection(RIGHT);
                        playerSnake.setNextDirection(RIGHT);
                    }
                }
            }
        }
    }

    // 更新游戏状态（蛇移动、碰撞检测、分数更新）
    void update() {
        if (!gameStarted) return;

        // 更新玩家蛇
        playerSnake.move(food, playerSnake.getHead() == food);
        // 吃到食物（蛇变长，加分）
        if (playerSnake.getHead() == food) {
            playerScore += 10;
            // 修复：中文输出用ASCII兼容格式，避免编码截断
            std::cout << "Wan Jia Chi Dao Shi Wu! Fen Shu: " << playerScore << std::endl;
            generateFood();
        }

        // 更新AI1蛇
        ai1Snake.setNextDirection(getAIDirection(ai1Snake, ai1Snake.getDirection(), ai1DirFrames));
        ai1Snake.move(food, ai1Snake.getHead() == food);
        if (ai1Snake.getHead() == food) {
            ai1Score += 5;
            // 中文输出用ASCII兼容格式，避免编码截断
            std::cout << "AI1 Chi Dao Shi Wu! Fen Shu: " << ai1Score << std::endl;
            generateFood();
        }

        // 更新AI2蛇
        ai2Snake.setNextDirection(getAI2Direction());
        ai2Snake.move(food, ai2Snake.getHead() == food);
        if (ai2Snake.getHead() == food) {
            ai2Score += 5;
            // 中文输出用ASCII兼容格式，避免编码截断
            std::cout << "AI2 Chi Dao Shi Wu! Fen Shu: " << ai2Score << std::endl;
            generateFood();
        }

        // 碰撞检测（游戏结束）
        if (playerSnake.checkSelfCollision(playerSnake.getHead()) ||
            ai1Snake.checkSelfCollision(ai1Snake.getHead()) ||
            ai2Snake.checkSelfCollision(ai2Snake.getHead()) ||
            playerSnake.checkCollision(ai1Snake.getHead()) ||
            playerSnake.checkCollision(ai2Snake.getHead()) ||
            ai1Snake.checkCollision(ai2Snake.getHead())) {
            gameOver = true;
            return;
        }
    }

    // 绘制游戏元素（蛇、食物、UI界面）
    void draw() {
        window.clear(sf::Color::Black);

        // 绘制顶部信息面板
        sf::RectangleShape topPanel(sf::Vector2f(WIDTH * BLOCK_SIZE, PANEL_HEIGHT));
        topPanel.setFillColor(sf::Color(20, 20, 20));
        window.draw(topPanel);

        // 绘制游戏边界
        sf::RectangleShape border(sf::Vector2f(WIDTH * BLOCK_SIZE, HEIGHT * BLOCK_SIZE));
        border.setOutlineColor(BORDER_COLOR);
        border.setOutlineThickness(1);
        border.setFillColor(sf::Color::Transparent);
        border.setPosition(0, PANEL_HEIGHT);
        window.draw(border);

        // 绘制所有蛇
        playerSnake.draw(window);
        ai1Snake.draw(window);
        ai2Snake.draw(window);

        // 绘制食物
        sf::RectangleShape foodRect(sf::Vector2f(BLOCK_SIZE, BLOCK_SIZE));
        foodRect.setPosition(static_cast<float>(food.x * BLOCK_SIZE), static_cast<float>(food.y * BLOCK_SIZE + PANEL_HEIGHT));
        foodRect.setFillColor(FOOD_COLOR);
        foodRect.setOutlineColor(FOOD_BORDER_COLOR);
        foodRect.setOutlineThickness(2);
        window.draw(foodRect);

        // 绘制文本
        if (font.getInfo().family != "") {
            // 菜单界面
            if (!gameStarted) {
                // 绘制单人模式按钮
                window.draw(singlePlayerButton);
                window.draw(singlePlayerText);

                // 绘制蛇颜色说明
                sf::Text infoText("Green: Player | Blue: AI1 | Purple: AI2", font, 16);
                infoText.setFillColor(sf::Color::White);
                sf::FloatRect textRect = infoText.getLocalBounds();
                infoText.setOrigin(textRect.width / 2, textRect.height / 2);
                infoText.setPosition(WIDTH * BLOCK_SIZE / 2, HEIGHT * BLOCK_SIZE + PANEL_HEIGHT - 40);
                window.draw(infoText);
            }
            // 游戏中界面
            else {
                // 玩家分数
                sf::Text playerText("Player: " + std::to_string(playerScore), font, 20);
                playerText.setFillColor(sf::Color::Yellow);
                playerText.setPosition(20, 15);
                window.draw(playerText);

                // AI1分数
                sf::Text ai1Text("AI1: " + std::to_string(ai1Score), font, 18);
                ai1Text.setFillColor(AISNAKE_COLOR);
                ai1Text.setPosition(WIDTH * BLOCK_SIZE - ai1Text.getLocalBounds().width - 20, 10);
                window.draw(ai1Text);

                // AI2分数
                sf::Text ai2Text("AI2: " + std::to_string(ai2Score), font, 18);
                ai2Text.setFillColor(ROBOTSNAKE_COLOR);
                ai2Text.setPosition(WIDTH * BLOCK_SIZE - ai2Text.getLocalBounds().width - 20, 30);
                window.draw(ai2Text);

                // 控制提示
                sf::Text controlText("W/A/S/D: Move | X: Quit ", font, 16);
                controlText.setFillColor(sf::Color::White);
                controlText.setPosition(10, HEIGHT * BLOCK_SIZE + PANEL_HEIGHT - 30);
                window.draw(controlText);
            }
        }
        window.display();
    }

    // 游戏主循环
    void run() {
        while (window.isOpen() && !gameOver) {
            handleInput();
            if (!gameOver) {
                update();
                draw();
            }
            sf::sleep(sf::milliseconds(gameSpeed));
        }

        // 游戏结束界面
        window.clear(sf::Color::Black);
        if (font.getInfo().family != "") {
            sf::Text gameOverText("Game Over!", font, 30);
            gameOverText.setFillColor(sf::Color::Red);
            gameOverText.setPosition(WIDTH * BLOCK_SIZE / 2 - 60, HEIGHT * BLOCK_SIZE / 2 - 60 + PANEL_HEIGHT);
            window.draw(gameOverText);

            sf::Text scoreText("Final Scores:", font, 22);
            scoreText.setFillColor(sf::Color::White);
            scoreText.setPosition(WIDTH * BLOCK_SIZE / 2 - 70, HEIGHT * BLOCK_SIZE / 2 - 20 + PANEL_HEIGHT);
            window.draw(scoreText);

            sf::Text playerFinal("Player: " + std::to_string(playerScore), font, 20);
            playerFinal.setFillColor(sf::Color::Yellow);
            playerFinal.setPosition(WIDTH * BLOCK_SIZE / 2 - 50, HEIGHT * BLOCK_SIZE / 2 + 10 + PANEL_HEIGHT);
            window.draw(playerFinal);

            sf::Text ai1Final("AI1: " + std::to_string(ai1Score), font, 20);
            ai1Final.setFillColor(AISNAKE_COLOR);
            ai1Final.setPosition(WIDTH * BLOCK_SIZE / 2 - 50, HEIGHT * BLOCK_SIZE / 2 + 40 + PANEL_HEIGHT);
            window.draw(ai1Final);

            sf::Text ai2Final("AI2: " + std::to_string(ai2Score), font, 20);
            ai2Final.setFillColor(ROBOTSNAKE_COLOR);
            ai2Final.setPosition(WIDTH * BLOCK_SIZE / 2 - 50, HEIGHT * BLOCK_SIZE / 2 + 70 + PANEL_HEIGHT);
            window.draw(ai2Final);

            sf::Text exitText("Press any key to exit", font, 18);
            exitText.setFillColor(sf::Color::White);
            exitText.setPosition(WIDTH * BLOCK_SIZE / 2 - 80, HEIGHT * BLOCK_SIZE / 2 + 110 + PANEL_HEIGHT);
            window.draw(exitText);
        }
        window.display();

        // 等待输入后关闭窗口
        sf::Event event;
        while (window.waitEvent(event)) {
            if (event.type == sf::Event::KeyPressed || event.type == sf::Event::MouseButtonPressed) {
                window.close();
                break;
            }
        }
    }
};

// 主函数
int main() {
    try {
        Game game;
        game.run();
    }
    catch (const std::exception& e) {
        std::cerr << "Error: " << e.what() << std::endl;
        return 1;
    }
    return 0;
}